package com.guanglan.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.guanglan.domain.SysPermission;
import com.guanglan.service.SysPermissionService;
import com.guanglan.utils.PageUtil;

/**
* @ClassName: PermissionController  
* @Description: TODO(用户管理类)  
* @author GuangLan good
* @date 2017年9月10日  
 */
@RequestMapping("/perm")
@Controller
public class PermissionController {
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SysPermissionService sysPermissionService;
	
	@RequestMapping("/premIndex")
	public String premIndex(@RequestParam(value="nowPage",required=false,defaultValue="1") Integer nowPage,
			Model model,@RequestParam(value="menuName",required=false,defaultValue="") String menuName) {
		int start = PageUtil.getStart(nowPage);  //获取到的开始查询索引
		int pageSize = PageUtil.pageSize; //获取页面容量
		Map<String,Object> params = new HashMap<>();
		params.put("start", start);
		params.put("pageSize", pageSize);
		params.put("menuName", menuName);
		List<SysPermission> perms = sysPermissionService.getSysPermissions(params);
		int count = sysPermissionService.getSysPermissionsCount(params);
		int countPage = PageUtil.countPage(count);
		String html = PageUtil.getPanationStringHtml(countPage, nowPage);
		model.addAttribute("html",html);
		model.addAttribute("perms",perms);
		return "perm/premIndex";
	}
	
	@RequestMapping("/addPermPage")
	public String addPermPage(Model model) {
		List<SysPermission> perms = sysPermissionService.getAllParentPerm();
		model.addAttribute("perms",perms);
		return "perm/edit";
	}
	
	@RequestMapping("/addPerm")
	public String addPerm(@RequestParam(value="menuName",required=false,defaultValue="") String menuName,
			@RequestParam(value="permission",required=false,defaultValue="") String permission,
			@RequestParam(value="menuUrl",required=false,defaultValue="") String menuUrl,
			@RequestParam(value="pid",required=false,defaultValue="") long pid) {
		
		SysPermission perm = new SysPermission();
		perm.setMenuName(menuName);
		perm.setMenuUrl(menuUrl);
		perm.setPermission(permission);
		perm.setPid(pid);
		int count = sysPermissionService.insertSelective(perm);
		log.info("更新菜单信息{}",count > 0 ? "成功":"失败");
		
		return "redirect:premIndex";
	}
	
	@RequestMapping("/delPerm")
	public String delPerm(@RequestParam(value="id",required=true,defaultValue="") long id) {
		int count = sysPermissionService.deleteByPrimaryKey(id);
		log.info("删除权限信息{}",count > 0 ? "成功":"失败");
		return "redirect:premIndex";
	}

}
